<?php

namespace app\common\model;

use think\Model;

class AgentArea extends Model
{
    // 表名
    protected $name = 'agent_area';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text',
	    'status_text',
	    'grade_text'
    ];
    
    const STATUS_Y = 1;
    const STATUS_N = 0;
    
    public static $statusList = [
        self::STATUS_Y => '正常',
	    self::STATUS_N => '禁用',
    ];
    
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}
    
	const GRADE_PROVINCE = 1;
	const GRADE_CITY = 2;
	const GRADE_AREA = 3;
	
	public static $gradeList = [
		self::GRADE_PROVINCE => '省代理',
		self::GRADE_CITY => '市代理',
		self::GRADE_AREA => '区代理'
	];

	public function getGradeTextAttr($value, $data) {
		$value = $value ? $value : $data['grade'];
		$list = self::$gradeList;
		return isset($list[$value]) ? $list[$value] : '';
	}

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function user(){
    	return $this->belongsTo('user', 'user_id', 'id', '', 'left')->setEagerlyType(0);
    }
    
    public function province(){
    	return $this->belongsTo('area', 'province_id', 'id', '', 'left')->setEagerlyType(0);
    }
    
    public function city(){
	    return $this->belongsTo('area', 'city_id', 'id', '', 'left')->setEagerlyType(0);
    }
    
	public function area()
	{
		return $this->belongsTo('area', 'area_id', 'id', '', 'left')->setEagerlyType(0);
	}
}
